import {
  autoScheduleByBatchPlanId,
  autoScheduleByBatchPlanIds,
  getWorkOrderInforByBatchPlanIdAndUnscheduled,
  getWorkOrderInforByBatchPlanIdAndScheduled,
  getProductPlansByWoId,
  getWorkOrderInforByPage,
  getBatchPlanByPage,
  updateProductPlanTime,
  manualSchedule,
  getStageByinfoId,
  autoScheduleByWoId,
  autoScheduleByBatchWoId,
  getStageByBatchPlanId,
  scheduleByWoIds,
  viewBaseInfo,
  uploadGuideBookFileInfo2,
} from '@/services/product/productManufactInfor';
import { getAllProcess } from '@/services/baseData/plantCapacityBase';
import {
  getAllPlantCapacityCalendar,
  getPlantCapacityBase,
} from '@/services/product/plantCapacityCalendar';
import PlantCapacityBaseStatisticsTable from './plantCapacityBaseStatisticsTable';
import ProTable from '@ant-design/pro-table';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ModalForm } from '@ant-design/pro-components';
import React, { useEffect, useState, useRef } from 'react';
import dayjs from 'dayjs';
import {
  Button,
  message,
  Tabs,
  DatePicker,
  Form,
  Spin,
  Modal,
  Row,
  Col,
  Upload,
  Select,
  Input,
} from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import './product.module.less';
import { Ellipsis } from '@/components/Ellipsis';
import weekday from 'dayjs/plugin/weekday';
import localeData from 'dayjs/plugin/localeData';
import classNames from 'classnames';
import {
  exportBatchProduct,
  exportWorkhourAndCycle,
  getBatchProductByPage,
  getBopCodeAndName,
  setBop,
  uploadWorkhourAndCycle,
  exportWorkhourAndCycleByProductId,
} from '@/services/design/productDesign';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { getProductTypeList } from '@/services/templateMaintain/inspectionTemplate';
import UnstandprocessInfo from '../design/unstandprocessInfo';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { releaseWorkOrderInfor } from '@/services/product/workOrderInfor';
import ProcessInfo from './processInfo';
import { object } from 'prop-types';
import moment from 'moment';
import useModal from 'antd/lib/modal/useModal';
import { useModel } from 'umi';
import log from '@/services/system/log';

dayjs.extend(weekday);
dayjs.extend(localeData);

const ProductManufactInfor: React.FC<{}> = () => {
  const [formTitle, setFormTitle] = useState('添加工艺路径'); //工艺弹窗标题
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit4, setModalVisit4] = useState(false); // 工时周期上传弹窗
  const ref = useRef(null);
  const dateFormat = 'YYYY-MM-DD';
  const [manuInfo, setManuInfo] = useState();
  const [manuAlreadyInfo, setAlreadyManuInfo] = useState();
  const [selections, setSelections] = useState([]);
  const [selectionsWorkHours, setSelectionsWorkHours] = useState([]);
  const [firstRecord, setFirstRecord] = useState({});
  const [lookorEditVisible, setLookorEditVisible] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [manufactInfo, setManufactInfo] = useState<any[]>(); //排程modal中的各个阶段时间
  const [extraManufactInfo, setExtraManufactInfo] = useState<any[]>(); //排程modal中补充的“生产分料”和“发货日期”
  const [loading, setLoading] = useState(false); //排程的加载
  const [confirmLoading, setConfirmLoading] = useState(false); //确认按钮后的加载动画
  // const [dateValues, setDateValues] = useState(
  //   Array(manufactInfo && manufactInfo.length).fill(null),
  // );
  const [lookOrEdit, setLookOrEdit] = useState<boolean>(true);
  const [changeOrManufact, setChangeOrManufact] = useState<string>('');
  const [dateValues, setDateValues] = useState([]);
  const [extraDateValues, setExtraDateValues] = useState([]);
  const [flag, setFlag] = useState(false);
  const [woId, setWoId] = useState('');
  const [titleDesc, setTitleDesc] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const { RangePicker } = DatePicker;
  //产能负荷图所需State
  const [uvData, setuvData] = useState([]);
  const [transformData, settransformData] = useState([]);
  const [optionsProcess, setoptionsProcess] = useState([]); //工序下拉框用到
  const [optionsbopCode, setoptionsbopCode] = useState([]);
  const [recordInfo, setrecordinfo] = useState<recordInfoType>();
  const [file, setFile] = useState();

  //工时部分
  const [theunStandTypeId, settheunStandTypeId] = useState();
  const [thebopcode, setthebopcode] = useState();
  const [thetypecode, setthetypecode] = useState();
  const [thetypename, setthetypename] = useState();
  const [thedesc, setthedesc] = useState();
  const [modalVisit3, setModalVisit3] = useState(false); // 工序工时弹窗
  const [modalVisit5, setModalVisit5] = useState(false); //未排程与已排程的工时弹窗
  const [batchProductId, setBatchProductId] = useState(); //用于保存排程中想要查看的柜体的batchId
  const [confirmLoading4, setConfirmLoading4] = useState(false);

  // 工艺指导书guidebooksubmit
  const [modalVisit6, setModalVisit6] = useState(false);
  const [confirmLoading6, setConfirmLoading6] = useState(false);

  //当前用户信息
  const { initialState } = useModel('@@initialState');
  const getManufactInfo = async () => {
    const result = await getBatchPlanByPage(
      JSON.stringify({
        current: 1,
        filters: [],
        pageSize: 20,
        sorters: [],
      }),
    );
    let temp: any[] = [];
    let tempAlready: any[] = [];
    await result.data.content.map(async (item: any) => {
      if (item === null) {
        return;
      }
      const resSon = await getWorkOrderInforByBatchPlanIdAndUnscheduled(item.id);
      if (resSon && resSon.data) {
        item = { ...item, children: resSon.data };
        temp.push(item);
      }
    });
    await result.data.content.map(async (item: any) => {
      if (item === null) {
        return;
      }
      const resSonAlready = await getWorkOrderInforByBatchPlanIdAndScheduled(item.id);
      if (resSonAlready && resSonAlready.data.length !== 0) {
        item = { ...item, children: resSonAlready.data };
        tempAlready.push(item);
      }
    });
    setTimeout(() => {
      temp = temp.filter((item: any) => item.children.length !== 0);
      tempAlready = tempAlready.filter((item: any) => item.children.length !== 0);
      setManuInfo(temp);
      setAlreadyManuInfo(tempAlready);
    }, 1000);
  };

  useEffect(() => {
    getManufactInfo();
    console.log('当前用户：', initialState);
  }, []);

  useEffect(() => {
    if (manufactInfo) {
      const initialDateValues = manufactInfo.map((item: any) => ({
        startDate: item.planManufactStartDate
          ? dayjs(item.planManufactStartDate, dateFormat)
          : null,
        endDate: item.planManufactEndDate ? dayjs(item.planManufactEndDate, dateFormat) : null,
      }));
      setDateValues(initialDateValues);
    }
  }, [manufactInfo]);

  useEffect(() => {
    if (extraManufactInfo) {
      const initialDateValues = extraManufactInfo.map((item: any) => ({
        stageName: item.stageName,
        startDate: item.stagePlanStartTime ? dayjs(item.stagePlanStartTime, dateFormat) : null,
        endDate: item.stagePlanEndTime ? dayjs(item.stagePlanEndTime, dateFormat) : null,
      }));
      setExtraDateValues(initialDateValues);
    }
  }, [extraManufactInfo]);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp: string[] = [];
      let firstBatchRow;
      if (selectedRows !== null) {
        selectedRows.map((item, index) => {
          temp.push({ id: item.id, infoId: item.infoId, batchPlanId: item.batchPlanId });
          if (index == 0) firstBatchRow = item;
        });
      }
      setFirstRecord(firstBatchRow);
      setSelections(temp);
    },
  };

  // 选中项目，导出工时模板
  const rowSelectionWorkHours = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp: string[] = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push({
            id: item.id,
            projectCode: item.projectCode,
            projectInfoId: item.infoId,
            projectName: item.projectName,
          });
        });
      }
      setSelectionsWorkHours(temp); //保存项目信息
    },
  };

  //获取工艺路径
  const getproductbop = async () => {
    // 获取工艺路径编号和名称
    const getcode = await getBopCodeAndName(null);
    const codeandname = [];
    getcode?.data.map((item: any, index: any) => {
      codeandname.push({ value: item.bopCode, label: item.bopName });
    });
    // console.log(codeandname);
    setoptionsbopCode(codeandname);
  };

  // 设置工艺路径
  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        console.log(res);
        const result = await setBop(res);
        if (result != null) {
          message.success('设置工艺路径成功');
        }
        setConfirmLoading(false);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading(false);
      });
  };

  const onFilesChange = async (file) => {
    setFile(file);
  };
  const beforeUpload = (file) => {
    setFile(file);
    return false;
  };

  // 上传工时模板提交
  const workhour_upload = async () => {
    setConfirmLoading4(true);
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        const result = await uploadWorkhourAndCycle({ file: res.file });
        if (result != null && result.code == 0) {
          message.success('上传成功');
          form.resetFields();
        }
        setConfirmLoading4(false);
        setModalVisit4(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading4(false);
      });
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
    },
    {
      title: '项目名称', //表头显示的名称
      dataIndex: 'projectName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
      align: 'center',
      // sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.projectName.localeCompare(b.projectName),
    },
    {
      title: '项目编号', //表头显示的名称
      dataIndex: 'projectCode', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
      align: 'center',
      // sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.projectCode.localeCompare(b.projectCode),
    },
    {
      title: 'ERP生产订单', //表头显示的名称
      dataIndex: 'erpMo',
      width: 120,
      align: 'center',
      // sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.erpMo.localeCompare(b.erpMo),
    },
    {
      title: `当前批次`,
      dataIndex: 'currentBatch',
      width: 50,
      search: false,
      align: 'center',
      sorter: true,
      render: (text, record) => (
        <>
          {text}/{record.batchCount}
        </>
      ),
    },
    {
      title: '批次交货日期', //表头显示的名称
      dataIndex: 'batchDeliveryDate',
      width: 120,
      search: false,
      align: 'center',
      // sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.batchDeliveryDate.localeCompare(b.batchDeliveryDate),
    },
    {
      title: '批次交货日期', //表头显示的名称
      dataIndex: 'batchDeliveryDate',
      width: 120,
      valueType: 'dateRange',
      hideInTable: true,
    },
    // {
    //   title: '批次编号', //表头显示的名称
    //   search: false,
    //   dataIndex: 'batchPlanCode',
    //   width: 120,
    //   render: (text) => <>{Ellipsis(text)}</>,
    //   sorter: (a, b) => a.batchPlanCode.localeCompare(b.batchPlanCode),
    // },
    {
      title: '柜体编号', //表头显示的名称
      dataIndex: 'batchProductCode',
      align: 'center',
      // sorter: true,
      width: 120,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.batchProductCode.localeCompare(b.batchProductCode),
    },
    {
      title: '工单编号', //表头显示的名称
      search: false,
      align: 'center',
      // sorter: true,
      dataIndex: 'wo',
      width: 120,
      render: (text) => <>{Ellipsis(text)}</>,
      sorter: (a, b) => a.wo.localeCompare(b.wo),
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      fixed: 'right',
      width: 80,
      render: (text, record, _, action) => {
        return !flag
          ? [
              <a
                key="editKey"
                /*                 disabled={!record.erpomo} */
                onClick={async () => {
                  /*                   if(!record.erpMo){
                                    message.error('ERP生产订单为空，无法排程')
                                    return
                                  } */
                  setLoading(true);
                  setLookorEditVisible(true);
                  setLookOrEdit(false);
                  setTitleDesc('排程');
                  setWoId(record.id);
                  const result = await getProductPlansByWoId(record.id);
                  setManufactInfo(result.data);
                  /* const result1 = await getStageByinfoId(record.infoId); */
                  const result1 = await getStageByBatchPlanId(record.batchPlanId);
                  const temp = result1.data.filter(
                    (item: { stageName: string }) =>
                      item.stageName === '生产分料' || item.stageName === '发货日期',
                  );
                  setExtraManufactInfo(temp);
                  setLoading(false);
                }}
              >
                排程
              </a>,
              <a
                key="processinfoKey1"
                onClick={() => {
                  setBatchProductId(record.batchProductId);
                  setModalVisit5(true);
                }}
              >
                工时
              </a>,
            ]
          : [
              <a
                key="lookKey"
                onClick={async () => {
                  setLoading(true);
                  setLookorEditVisible(true);
                  setLookOrEdit(true);
                  setTitleDesc('查看');
                  setWoId(record.id);
                  const result = await getProductPlansByWoId(record.id);
                  setManufactInfo(result.data);
                  /* const result1 = await getStageByinfoId(record.infoId); */
                  const result1 = await getStageByBatchPlanId(record.batchPlanId);
                  const temp = result1.data.filter(
                    (item: { stageName: string }) =>
                      item.stageName === '生产分料' || item.stageName === '发货日期',
                  );
                  setExtraManufactInfo(temp);
                  setLoading(false);
                }}
              >
                查看
              </a>,
              <a
                key="changeKey"
                onClick={async () => {
                  setLoading(true);
                  setLookorEditVisible(true);
                  setLookOrEdit(false);
                  setTitleDesc('计划变更');
                  setWoId(record.id);
                  const result = await getProductPlansByWoId(record.id);
                  setManufactInfo(result.data);
                  /* const result1 = await getStageByinfoId(record.infoId); */
                  const result1 = await getStageByBatchPlanId(record.batchPlanId);
                  const temp = result1.data.filter(
                    (item: { stageName: string }) =>
                      item.stageName === '生产分料' || item.stageName === '发货日期',
                  );
                  setExtraManufactInfo(temp);
                  setLoading(false);
                }}
              >
                计划变更
              </a>,
              <a
                key="processinfoKey1"
                onClick={() => {
                  setBatchProductId(record.batchProductId);
                  setModalVisit5(true);
                }}
              >
                工时
              </a>,
            ];
      },
    },
  ];

  // 工艺工时、未维护
  const tobeSubmitted: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 185,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 120,
    },
    {
      title: '维护状态',
      dataIndex: 'isStdWorkHourUploaded',
      align: 'center',
      sorter: true,
      width: 100,
      search: false,
      render: (text, record, _, action) => {
        return <div>{record.isStdWorkHourUploaded == 1 ? '已维护' : '未维护'}</div>;
      },
    },
    {
      title: '指导书上传标识',
      dataIndex: 'isGuideBookUploaded',
      align: 'center',
      sorter: true,
      width: 140,
      search: false,
      render: (text, record, _, action) => {
        return <div>{record.isGuideBookUploaded == 1 ? '已上传' : '未上传'}</div>;
      },
    },
    {
      title: '批次交货日期',
      dataIndex: 'batchDeliveryDate',

      valueType: 'date',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 120,
      search: false,
    },
    {
      title: '批次编号',
      dataIndex: 'batchPlanCode',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 180,
    },
    // {
    //   title: '主计划编号',
    //   dataIndex: 'masterPlanCode',
    // },
    {
      title: '柜体编号',
      dataIndex: 'productCode',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 190,
    },
    {
      title: '柜体描述',
      dataIndex: 'productDesc',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 200,
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproduct = await getProductTypeList(null);
        const productOptionContract: any[] = [];
        getproduct.data.map((item: any, index: any) => {
          productOptionContract.push({ value: item, label: item });
        });
        return productOptionContract;
      },
    },
    // {
    //   title: '是否标准柜体',
    //   dataIndex: 'isStandard',

    //   valueType: 'select',
    //   request: async () => [
    //     { label: '是', value: 1 },
    //     { label: '否', value: 0 },
    //   ],
    //   render: (text, record, _, action) => {
    //     return <div>{record.isStandard == 1 ? '是' : '否'}</div>;
    //   },
    //   align: 'center',
    //   sorter: true,
    //   width: 120,
    // },
    {
      title: '技术工程师',
      dataIndex: 'engineer',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    /*     {
          title: '审核状态',
          dataIndex: 'reviewState',
    
          search: false,
          width: 100,
          align: 'center',
          sorter: true,
          valueType: 'select',
          request: async () => [
            { label: '待提交', value: 0 },
            { label: '待审批', value: 1 },
            { label: '已审批', value: 2 },
            { label: '已驳回', value: 3 },
          ],
          render: (text, record, _, action) => {
            return (
              <div>
                {record.reviewState == 0
                  ? '待提交'
                  : record.reviewState == 1
                  ? '待审批'
                  : record.reviewState == 2
                  ? '已审批'
                  : '已驳回'}
              </div>
            );
          },
        },
        {
          title: '状态',
          dataIndex: 'state',
    
          align: 'center',
          sorter: true,
          width: 90,
          valueType: 'select',
          request: async () => [
            { label: '未下发', value: 0 },
            { label: '设计中', value: 1 },
            { label: '工单下发', value: 2 },
            { label: '生产中', value: 3 },
          ],
          render: (text, record, _, action) => {
            return (
              <div>
                {record.state == 0
                  ? '未下发'
                  : record.state == 1
                  ? '设计中'
                  : record.state == 2
                  ? '工单下发'
                  : '生产中'}
              </div>
            );
          },
        },
        {
          title: 'BOM上传',
          dataIndex: 'bomId',
    
          align: 'center',
          sorter: true,
          width: 100,
          search: false,
          render: (text, record, _, action) => {
            return <div>{record.bomId == null ? '未上传' : '已上传'}</div>;
          },
        },
        {
          title: '图纸上传',
          dataIndex: 'drawingId',
    
          align: 'center',
          sorter: true,
          width: 100,
          search: false,
          render: (text, record, _, action) => {
            return <div>{record.drawingId == null ? '未上传' : '已上传'}</div>;
          },
        }, */
    {
      title: '工艺路径',
      dataIndex: 'bopCode',

      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '设计计划开始',
      dataIndex: 'planDesignStartDate',

      search: false,
      valueType: 'date',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '设计计划结束',
      dataIndex: 'planDesignEndDate',

      search: false,
      valueType: 'date',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '计划设计工时',
    //   dataIndex: 'planDesignWh',
    //
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '实际设计开始',
      dataIndex: 'actualKickoffStartDate',

      search: false,
      valueType: 'date',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 150,
      render: (text, record, _, action) => [
        <a
          key="productbopKey1"
          /*           disabled={record.isPoReleased == 1} */
          onClick={async () => {
            /*             if (record.isPoReleased == 1) {
                          message.warning('不能再次修改工艺路径');
                        } else if (record.bopIsChange == 1) {
                          message.warning('不能再次修改工艺路径');
                        } else { */
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('添加工艺路径');
            form.setFieldsValue({
              bopCode: optionsbopCode[0].value,
              unStandTypeId: record.id,
              productCode: record.productCode,
              productDesc: record.productDesc,
            });
            /*             } */
          }}
        >
          工艺
        </a>,
        <a
          key="processinfoKey1"
          disabled={record.isPoReleased == 1}
          onClick={() => {
            if (record.isPoReleased == 1) {
              message.warning('不能再次修改工时');
            } else {
              settheunStandTypeId(record.id);
              setthebopcode(record.bopCode);
              setthetypecode(record.productCode);
              setthetypename(record.productType);
              setthedesc(record.productDesc);
              setModalVisit3(true);
            }
          }}
        >
          工时
        </a>,
        <a
          key="guidebookKey"
          onClick={async () => {
            const getuserlist = await viewBaseInfo(null);
            setFormTitle('上传指导书');
            form.setFieldsValue({
              batchProductId: record.id,
              instruction: '',
              file: '',
              uploaderName: getuserlist.data.name,
              uploaderId: getuserlist.data.id,
            });
            setModalVisit6(true);
          }}
        >
          指导书
        </a>,
      ],
    },
  ];

  // 工艺指导书上传
  const guidebooksubmit = async () => {
    setConfirmLoading6(true);
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        res.uploadTime = moment().format('YYYY-MM-DD HH:mm:ss');
        const result = await uploadGuideBookFileInfo2(res);
        if (result != null) {
          message.success('上传成功');
          form.resetFields();
        }
        setConfirmLoading6(false);
        setModalVisit6(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading6(false);
      });
  };

  // const handleClickRow = async (record: any) => {
  //   const result = await getWorkOrderInforByBatchPlanId(record.id);
  //   console.log(result, 'tesult');
  //   //setManuInfo
  //   const temp = manuInfo?.map((item: any) => {
  //     if (item.id === record.id) {
  //       item = { ...item, children: result.data };
  //     }
  //     return item; // 返回更新后的对象
  //   });
  //   setManuInfo(temp);
  //   console.log(temp, 'manuInfo');
  // };

  type tabsType = {
    key: string;
    name: string;
    label: string;
    content: JSX.Element;
  };
  const items1: tabsType[] = [
    {
      key: '0',
      name: 'tab1',
      label: '未维护',
      content: (
        <div>
          <ProTable
            headerTitle="柜体工艺工时维护"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={tableSearchPublicConfig}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="workhour_button"
                type="primary"
                onClick={async () => {
                  console.log(selectionsWorkHours);
                  //去除重复项
                  let hash = {};
                  var newArr = selectionsWorkHours.reduce((prev, next) => {
                    hash[next.projectCode]
                      ? ''
                      : (hash[next.projectCode] = true && prev.push(next.id));
                    return prev;
                  }, []);
                  // console.log(selections,'处理前的项目信息');
                  console.log(newArr, '处理后的项目信息');
                  exportWorkhourAndCycleByProductId(newArr).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = URL.createObjectURL(res);
                    const filenmae = '工时模板.xls';
                    aLink.setAttribute('download', filenmae);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                  // if (newArr.length === 0) {
                  //   message.info('请选择柜体');
                  // } else if (newArr.length > 1) {
                  //   message.info('暂不支持批量下载');
                  // } else {
                  //   exportWorkhourAndCycle(newArr[0]).then((res) => {
                  //     const aLink = document.createElement('a');
                  //     document.body.appendChild(aLink);
                  //     aLink.style.display = 'none';
                  //     aLink.href = window.URL.createObjectURL(res);
                  //     const filenmae = '工时模板_' + newArr[0].projectName + '.xls';
                  //     aLink.setAttribute('download', filenmae);
                  //     aLink.click();
                  //     document.body.removeChild(aLink);
                  //   });
                  // }
                }}
              >
                工时模板下载
              </Button>,
              <Button
                key="workhour_upload_button"
                type="primary"
                onClick={() => {
                  setModalVisit4(true);
                  form.setFieldsValue({
                    file: '',
                  });
                }}
              >
                工时上传
              </Button>,
              <Button
                key="button1"
                icon={<PlusOutlined />}
                onClick={() => {
                  const res = { reviewState: 0 };
                  const filters = filterTranNew(res);
                  exportBatchProduct({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `BatchProduct.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const res = { ...params, reviewState: 2, isStandard: 0 };
              const sorters = sortTran(sort);
              // const filters = {
              //   andOr: 'and',
              //   field: 'isStdWorkHourUploaded',
              //   operator: 'eq',
              //   value: '0',
              // };
              const filtersnew = filterTranNew(res);
              // filtersnew.push(filters);
              const result = await getBatchProductByPage({
                ...params,
                sorters: sorters,
                filters: filtersnew,
              });
              // 筛选条件：工时或指导书未上传 isGuideBookUploaded=0||isStdWorkHourUploaded=0
              const temp = result.data.content.filter(
                (item: any) => item.isGuideBookUploaded == 0 || item.isStdWorkHourUploaded == 0,
              );
              await getproductbop();
              return {
                data: temp,
                total: temp.totalElements,
                success: result.success,
              };
            }}
            columns={tobeSubmitted}
            scroll={{ x: 2730, y: 450 }}
            rowSelection={{
              selectionsWorkHours,
              ...rowSelectionWorkHours,
            }}
          />
        </div>
      ),
    },
    {
      key: '1',
      name: 'tab2',
      label: `未排程`,
      content: (
        <ProTable
          search={{
            labelWidth: 100,
            defaultCollapsed: true,
          }}
          headerTitle="未排程工单"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          toolBarRender={(action, { selectedRows }) => [
            <>
              <Button
                key="button"
                type="primary"
                onClick={() => {
                  message.success('同步成功');
                  actionRef.current!.reload();
                }}
              >
                工单同步
              </Button>
              <Button
                key="button"
                onClick={async () => {
                  if (selections.length) {
                    setLoading(true);
                    setTitleDesc('批量排程');
                    setLookOrEdit(false);
                    setLookorEditVisible(true);
                    const result = await getProductPlansByWoId(selections[0].id);
                    setManufactInfo(result.data);
                    console.log(selections[0]);
                    /* const result1 = await getStageByinfoId(selections[0].infoId); */
                    const result1 = await getStageByBatchPlanId(selections[0].batchPlanId);
                    const temp = result1.data.filter(
                      (item: { stageName: string }) =>
                        item.stageName === '生产分料' || item.stageName === '发货日期',
                    );
                    setExtraManufactInfo(temp);
                    setLoading(false);
                  } else {
                    message.info('请先选择要排程的批次');
                  }
                }}
                type="primary"
              >
                批量排程
              </Button>
            </>,
          ]}
          rowSelection={{
            ...rowSelection,
          }}
          request={async (params = {}, sort, filter) => {
            const sorters = sortTran(sort);
            const filters = {
              andOr: 'and',
              field: 'scheduledFlag',
              operator: 'eq',
              value: '1',
            };
            const filtersnew = filterTranNew(params);
            filtersnew.push(filters);
            const result = await getWorkOrderInforByPage({
              ...params,
              sorters: sorters,
              filters: filtersnew,
            });
            console.log(result.data.content);
            setFlag(false);
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          pagination={{
            defaultPageSize: 100,
            defaultCurrent: 1,
            pageSizeOptions: [100, 500, 1000],
            showSizeChanger: true,
          }}
          scroll={{ x: 1000, y: 450 }}
        />
      ),
    },
    {
      key: '2',
      name: 'tab3',
      label: `已排程`,
      content: (
        <ProTable
          headerTitle="已排程工单"
          search={{
            labelWidth: 100,
            defaultCollapsed: true,
          }}
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          request={async (params = {}, sort, filter) => {
            const sorters = sortTran(sort);
            console.log('filter', params);
            const filters = filterTranNew(params);
            filters.push({
              andOr: 'and',
              field: 'scheduledFlag',
              operator: 'eq',
              value: '2',
            });
            // const filters = [
            //   {
            //     andOr: 'and',
            //     field: 'scheduledFlag',
            //     operator: 'eq',
            //     value: '2',
            //   },
            // ];

            const result = await getWorkOrderInforByPage({
              ...params,
              sorters: sorters,
              filters: filters,
            });
            setFlag(true);
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          pagination={{
            defaultPageSize: 100,
            defaultCurrent: 1,
            pageSizeOptions: [100, 500, 1000],
            showSizeChanger: true,
          }}
          scroll={{ x: 1000, y: 450 }}
        />
      ),
    },
  ];

  function Manufactor() {
    return (
      <>
        {manufactInfo &&
          manufactInfo.map((item: any, index: number) => (
            <div key={item.productManufactInforId} className="row-productManufactInfor">
              <div className="order-name">{item.processName}</div>
              {dateValues[index] && ( // 添加条件判断，确保dateValues[index]不为undefined
                <RangePicker
                  disabled={lookOrEdit}
                  onChange={(value, dateString) => {
                    console.log(value, 'values');
                    console.log(dateString, 'dateString');
                    const newDateValues = [...dateValues];
                    manufactInfo[index].planManufactEndDate = dateString[1];
                    manufactInfo[index].planManufactStartDate = dateString[0];
                    /*                     item.planManufactEndDate = dateString[1];
                    item.planManufactStartDate = dateString[0]; */
                    newDateValues[index] = {
                      startDate: value[0],
                      endDate: value[1],
                    };
                    //如果不是生产准备的日期
                    if (index != 0) {
                      const dayBeforeEndDate = dayjs(value[0], dateFormat).subtract(1, 'day');
                      console.log(dayBeforeEndDate, 'dayBeforeEndDate');
                      console.log(dayBeforeEndDate.format(dateFormat), 'string');
                      if (
                        dayBeforeEndDate.isBefore(newDateValues[index - 1].startDate) &&
                        newDateValues[index - 1].startDate
                      ) {
                        message.error(
                          '该操作会导致某项的结束日期小于开始日期，请从某项的开始日期进行调整',
                        );
                        return;
                      } else {
                        newDateValues[index - 1] = {
                          ...newDateValues[index - 1],
                          endDate: dayBeforeEndDate,
                        };
                        manufactInfo[index - 1].planManufactEndDate =
                          dayBeforeEndDate.format(dateFormat);
                      }
                    }
                    setDateValues(newDateValues);
                  }}
                  style={{ width: '500px' }}
                  value={[dateValues[index].startDate, dateValues[index].endDate]}
                  format={dateFormat}
                />
              )}
            </div>
          ))}
        <Row className="row-productManufactInfor">
          {extraManufactInfo &&
            extraManufactInfo.map((item: any, index: number) => (
              <Col span={9} offset={2}>
                <p className="order-name-bottom">{item.stageName}</p>
                {extraDateValues[index] && ( // 添加条件判断，确保dateValues[index]不为undefined
                  <DatePicker
                    disabled
                    style={{ width: '185px' }}
                    value={
                      extraDateValues[index].stageName === '生产分料'
                        ? extraDateValues[index].startDate
                        : extraDateValues[index].endDate
                    }
                    format={dateFormat}
                  />
                )}
              </Col>
            ))}
        </Row>
      </>
    );
  }

  const items2: tabsType[] = [
    {
      key: '0',
      label: '排程',
      name: 'tab1',
      content: (
        <div className="manufactor">
          <Manufactor />
        </div>
      ),
    },
    {
      key: '1',
      label: '产能负荷图',
      name: 'tab2',
      content: <PlantCapacityBaseStatisticsTable />,
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        destroyInactiveTabPane
        type="card"
        onChange={(e) => {
          if (e === '1') {
            setFlag(false);
          } else if (e === '2') {
            setFlag(true);
          }
        }}
        defaultActiveKey="0"
        items={items1.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />
      <Modal
        open={lookorEditVisible}
        title={titleDesc}
        confirmLoading={confirmLoading}
        width={titleDesc === '排程' || titleDesc === '批量排程' ? 1200 : 750}
        destroyOnClose
        onCancel={() => {
          setManufactInfo([]);
          setLookorEditVisible(false);
        }}
        onOk={async () => {
          setConfirmLoading(true);
          const devices = dayjs(manufactInfo[1].planManufactStartDate, dateFormat); //器件分料的开始日期
          const product = dayjs(extraManufactInfo[0].stagePlanStartTime, dateFormat); //生产分料日期
          let result;
          const flag = dayjs(devices).isBefore(product); //判断器件分料的开始日期是否早于生产分料日期
          if (flag) {
            message.error('器件分料的开始日期应该晚于生产分料日期！');
            setConfirmLoading(false);
            return;
          }
          if (titleDesc == '排程') {
            //console.log(manufactInfo,'manufactInfo');
            result = await manualSchedule({
              productPlanTimeDto: manufactInfo,
              woId: woId,
              operatorId: initialState?.currentUser?.id,
              operatorName: initialState?.currentUser?.name,
            });
          } else if (titleDesc == '计划变更') {
            result = await updateProductPlanTime({
              productPlanTimeDto: manufactInfo,
              woId: woId,
            });
          } else if (titleDesc == '批量排程') {
            const batchPlanIds: string[] = [];
            selections.map((s) => {
              if (s === null) {
                return;
              }
              batchPlanIds.push(s.id);
            });
            console.log(batchPlanIds, '批量排程');
            /* result = await autoScheduleByBatchWoId(batchPlanIds); */
            result = await scheduleByWoIds({
              productPlanTimeDto: manufactInfo,
              woIds: batchPlanIds,
            });
            setSelections([]);
            actionRef.current?.reload();
            actionRef.current?.clearSelected();
          } else {
            setLookorEditVisible(false);
            setConfirmLoading(false);
            return;
          }
          if (result && result.code === 0) {
            message.success(result.message);
            setLookorEditVisible(false);
          }
          setConfirmLoading(false);
          actionRef.current?.reload();
        }}
      >
        <Spin spinning={loading}>
          {titleDesc === '排程' || titleDesc === '批量排程' ? (
            <Tabs
              destroyInactiveTabPane
              type="card"
              style={{ overflowX: 'hidden' }}
              defaultActiveKey="0"
              items={items2.map((item, i) => {
                const id = String(i + 1);
                return {
                  label: item.label,
                  key: id,
                  children: <div>{item.content}</div>,
                };
              })}
            />
          ) : (
            <Manufactor />
          )}
        </Spin>
      </Modal>
      {/* 工艺 */}
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="批次柜体id"
            name="unStandTypeId"
            rules={[{ required: true, message: '请输入批次柜体id!' }]}
            hidden={true}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="柜体编号"
            name="productCode"
            // rules={[{ required: true, message: '请输入柜体编号!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="柜体描述"
            name="productDesc"
            // rules={[{ required: true, message: '请输入柜体描述!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="工艺路径"
            name="bopCode"
            rules={[{ required: true, message: '请选择工艺路径!' }]}
          >
            <Select
              disabled={recordInfo?.reviewState == 1}
              placeholder="请选择工艺路径"
              onChange={(value) => {}}
              options={optionsbopCode}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 工时 */}
      <Modal
        title="工序工时"
        width={1200}
        open={modalVisit3}
        onCancel={() => {
          setModalVisit3(false);
        }}
        destroyOnClose
        footer={null}
      >
        <UnstandprocessInfo
          bopcode={thebopcode}
          unStandTypeId={theunStandTypeId}
          typecode={thetypecode}
          typename={thetypename}
          desc={thedesc}
        />
      </Modal>

      {/* 排程中工时查看 */}
      <Modal
        title="工序工时"
        width={1200}
        open={modalVisit5}
        onCancel={() => {
          setModalVisit5(false);
        }}
        destroyOnClose
        footer={null}
      >
        <ProcessInfo batchProductId={batchProductId} />
      </Modal>

      {/* 工时上传 */}
      <Modal
        title="上传工时周期"
        visible={modalVisit4}
        onOk={workhour_upload}
        confirmLoading={confirmLoading4}
        onCancel={() => setModalVisit4(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传工时周期文件!' }]}
          >
            <Upload
              accept="application"
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={'上传工艺指导书'}
        visible={modalVisit6}
        onOk={guidebooksubmit}
        confirmLoading={confirmLoading6}
        onCancel={() => setModalVisit6(false)}
        width={600}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="batchProductId" name="batchProductId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="指导书上传"
            name="file"
            rules={[{ required: true, message: '请上传指导书!' }]}
          >
            <Upload
              file-list="fileList"
              // getValueFromEvent={normFile}
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传指导书</Button>
            </Upload>
          </Form.Item>
          <Form.Item
            label="文件说明"
            name="instruction"
            rules={[{ required: true, message: '请输入文件说明!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="上传人"
            name="uploaderName"
            rules={[{ required: true, message: '请输入上传人!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item label="上传人id" name="uploaderId" hidden>
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>
      {/* <Modal
        open={printOpen}
        title="打印预览"
        width={1200}
        onOk={() => {
          setPrintOpen(false);
        }}
        onCancel={() => {
          setPrintOpen(false);
        }}
      >
        <div style={{ height: 600 }}>
          <iframe
            src="http://47.100.77.32:9000/standfile/null%2BCoevolutionary_Particle_Swarm_Optimization_With_Bottleneck_Objective_Learning_Strategy_for_Many-Objective_Optimization.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20230404%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230404T085113Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=ce54cfa3ac38955a5839bc2a9a12b98d0f18e3c1c80d62dd6c908781fb444541"
            frameborder="0"
            width={1200}
            height={600}
          ></iframe>
        </div>
      </Modal> */}
    </PageHeaderWrapper>
  );
};

export default ProductManufactInfor;
